package com.tarena.lbs.basic.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.web.repository.AdminRepository;
import com.tarena.lbs.basic.web.repository.BusinessRepository;
import com.tarena.lbs.basic.web.repository.StoreRepository;
import com.tarena.lbs.basic.web.utils.AuthenticationContextUtils;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.attach.param.PicUpdateParam;
import com.tarena.lbs.pojo.basic.param.StoreParam;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.po.BusinessPO;
import com.tarena.lbs.pojo.basic.po.StorePO;
import com.tarena.lbs.pojo.basic.query.StoreQuery;
import com.tarena.lbs.pojo.basic.vo.StoreVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StoreService {
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private StoreRepository storeRepository;
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private LoginService loginService;
    @DubboReference
    private AttachApi attachApi;

    public PageResult<StoreVO> getAllStorePageList(StoreQuery query) throws BusinessException {
        //1.准备一个PageResult 用于封装数据返回
        PageResult<StoreVO> voPage = new PageResult<>();
        voPage.setTotal(100L);
        //2.获取登录用户角色
        UserPrinciple userPrinciple = getUserPrinciple();
        //2.1  如果是shop角色，读取admin详情，获取businessId
        if (userPrinciple.getRole()==Roles.SHOP){
            //说明请求用户为商家管理员
            AdminPO adminPO = adminRepository.getById(userPrinciple.getId());
            Asserts.isTrue(adminPO==null,new BusinessException("-2","商家账号不存在"));
            Integer businessId = adminPO.getBusinessId();
            query.setBusinessId(businessId);
        }
        //3.  查询列表
        List<StorePO> pos = getStoreList(query);
        //4. 查询pos转化为vos，封装
        if (pos != null && pos.size() > 0){
            voPage.setObjects(pos.stream().map(po->{
                StoreVO vo = new StoreVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList()));
        }
        return voPage;
    }

    private List<StorePO> getStoreList(StoreQuery query) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (query.getBusinessId() != null){
            queryWrapper.eq("business_id",query.getBusinessId());
        }
        List list = storeRepository.list(queryWrapper);
        return list;
    }

    private UserPrinciple getUserPrinciple() throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户解析失败"));
        return userPrinciple;
    }

    public void saveStore(StoreParam storeParam) throws BusinessException {
        //1. 角色检查，只能说商家管理员
        checkRole(Roles.SHOP);
        //2. 检查商家是否存在
        checkBusiness(storeParam.getBusinessId());
        //3. 将param转化成po
        StorePO storePO = param2po(storeParam);
        //4. 将storePO 写入数据库，同时写入es，交给仓储层处理
        storeRepository.saveData(storePO);
        //5. 绑定图片 logo 300  images  400   storeId
        bindPictures(storeParam,storePO.getId());
    }

    private void bindPictures(StoreParam storeParam, Integer businessId) {
        List<PicUpdateParam> picParams = new ArrayList<>();
        PicUpdateParam logoParam = new PicUpdateParam();
        logoParam.setBusinessType(300);
        logoParam.setBusinessId(businessId);
        logoParam.setId(Integer.valueOf(storeParam.getStoreLogo()));
        picParams.add(logoParam);
        List<PicUpdateParam> imageParams = null;
        List<String> storeImagesIds = storeParam.getStoreImagesIds();
        imageParams = storeImagesIds.stream().map(image->{
            PicUpdateParam imageParam = new PicUpdateParam();
            imageParam.setBusinessType(400);
            imageParam.setBusinessId(businessId);
            imageParam.setId(Integer.valueOf(image));
            return imageParam;
        }).collect(Collectors.toList());
        picParams.addAll(imageParams);
        attachApi.batchUpdateBusiness(picParams);
    }

    private StorePO param2po(StoreParam storeParam) {
        StorePO storePO = new StorePO();
        BeanUtils.copyProperties(storeParam,storePO);
        //店铺状态 前端没传 0 正常 ，1 禁用
        storePO.setStoreStatus(0);
        //创建时间
        storePO.setCreateTime(new Date());
        storePO.setUpdateTime(new Date());
        //地理位置信息
        storePO.setStoreLatitude(storeParam.getLatitude());
        storePO.setStoreLongitude(storeParam.getLongitude());
        //手动将入参的门店图片数组，转化为使用  ，  隔开的字符串
        List<String> storeImagesIds = storeParam.getStoreImagesIds();
        String images = "";
        if (storeImagesIds != null && storeImagesIds.size() > 0){
            // 循环遍历，判断元素是否到最后一个
            for (int i = 0 ;i<storeImagesIds.size();i++){
                //最后一个元素不拼接 ，
                if (i == storeImagesIds.size()-1){
                    images = images + storeImagesIds.get(i);
                }else {
                    images = images + storeImagesIds.get(i) + ",";
                }
            }
        }
        log.info("当前店铺:{},门店图片images:{}",storeParam.getStoreName(),images);
        storePO.setStoreImagesId(images);
        return storePO;
    }

    private void checkBusiness(Integer businessId) throws BusinessException {
        BusinessPO businessPO = businessRepository.getById(businessId);
        Asserts.isTrue(businessPO==null,new BusinessException("-2","商家不存在"));
    }

    private void checkRole(Roles role) throws BusinessException {
        //1.获取上游传入的登录用户信息
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null,new BusinessException("-2","用户解析失败！"));
        Roles userRole = userPrinciple.getRole();
        Asserts.isTrue(role != userRole,new BusinessException("-2","只有商家管理员才能增加店铺！"));
    }
}
